package com.xiaoshuidi.cloud.module.system.dal.mysql.oauth2;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.mybatis.core.mapper.BaseMapperX;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.module.system.controller.admin.oauth2.vo.token.OAuth2AccessTokenPageReqVO;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.oauth2.OAuth2AccessTokenWithUserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface OAuth2AccessTokenMapper extends BaseMapperX<OAuth2AccessTokenDO> {

    @Select("select t.*, ifnull(u.nickname, t.nickname) as nickname1, u.dept_id, ifnull(u.mobile, t.mobile) as mobile1 " +
            "from system_oauth2_access_token t left join system_users u on t.user_id = u.id " +
            "where t.access_token = #{accessToken}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "accessToken", column = "access_token"),
            @Result(property = "refreshToken", column = "refresh_token"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "userType", column = "user_type"),
            @Result(property = "clientId", column = "client_id"),
            @Result(property = "scopes", column = "scopes", typeHandler = JacksonTypeHandler.class),
            @Result(property = "expiresTime", column = "expires_time"),
            @Result(property = "nickname", column = "nickname1"),
            @Result(property = "deptId", column = "dept_id"),
            @Result(property = "mobile", column = "mobile1"),
    })
    OAuth2AccessTokenWithUserInfo selectByAccessTokenWithUserInfo(String accessToken);

    default OAuth2AccessTokenDO selectByAccessToken(String accessToken) {
        return selectOne(OAuth2AccessTokenDO::getAccessToken, accessToken);
    }

    default List<OAuth2AccessTokenDO> selectListByRefreshToken(String refreshToken) {
        return selectList(OAuth2AccessTokenDO::getRefreshToken, refreshToken);
    }

    default PageResult<OAuth2AccessTokenDO> selectPage(OAuth2AccessTokenPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<OAuth2AccessTokenDO>()
                .eqIfPresent(OAuth2AccessTokenDO::getUserId, reqVO.getUserId())
                .eqIfPresent(OAuth2AccessTokenDO::getUserType, reqVO.getUserType())
                .likeIfPresent(OAuth2AccessTokenDO::getClientId, reqVO.getClientId())
                .gt(OAuth2AccessTokenDO::getExpiresTime, LocalDateTime.now())
                .orderByDesc(OAuth2AccessTokenDO::getId));
    }

}
